package com.danger.model.action;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.provider.MediaStore;

import com.danger.model.entity.Song;
import com.danger.model.listener.OnScanMusicListener;
import com.danger.util.CheckSD;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 俊 on 2016/8/15.
 */
public class PlayModelImpl implements PlayModel {

    private Context context;

    public PlayModelImpl(Context context) {
        this.context = context;
    }

    @Override
    public void getMusic(OnScanMusicListener listener) {
        if (CheckSD.isAvaiable()) {
            List<Song> songs = new ArrayList<>();
            ContentResolver resolver = context.getContentResolver();
            Cursor cursor = resolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
            int position = 0;
            while (cursor.moveToNext()) {
                long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
                long albumid = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
                String name = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
                String album = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
                String artist = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
                String url = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
                long duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));
                long size = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE));

                Song song = new Song();
                song.setPosition(position);
                song.setId(id);
                song.setAlbumid(albumid);
                song.setName(name);
                song.setAlbum(album);
                song.setArtist(artist);
                song.setUrl(url);
                song.setDuration(duration);
                song.setSize(size);

                songs.add(song);
                position++;
            }
            listener.onSuccess(songs);
        } else {
            listener.onError("SD卡不可用！");
        }
    }
}
